package cassandra;

import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.ObjectName;

import utils.CassandraJMXProxy;
import utils.RingUtils;
import exception.RuleBasedMonitoringException;
public class LoadBalance extends Action {
	Ring ring;
	public LoadBalance (Ring ring) {
		this.ring = ring;
	}

	public void call() throws RuleBasedMonitoringException {
		super.call();

		List<BigInteger>  tokenList = RingUtils.getInstance().generateToken(ring.getNodeNumber());
		Map<String, String> ipNodes = ring.getLoadMap();
		int index = 0;
		for (String ip : ipNodes.keySet()) {
			try {
				BigInteger tokenBI = tokenList.get(index);
				Object [] params1 = {tokenBI.toString()};
				String [] signature = {String.class.getName()};
				try{
					ObjectName node   =	CassandraJMXProxy.getInstance().getObjectName(InetAddress.getByName(ip), CassandraJMXProxy.getInstance().storageServiceName);
					CassandraJMXProxy.getInstance().callOperation(node,"move", params1, signature);

				}
				catch (RuleBasedMonitoringException e){ 

					Logger.getLogger(LoadBalance.class.getName()).log(Level.SEVERE, null, e.getCause());						
					continue;


				}


			}
			catch (UnknownHostException e){

				throw (new RuleBasedMonitoringException(e));
			} 

			index++;
		}

		//Logger.getLogger(LoadBalance.class.getName()).log(Level.INFO, null, "Load balance action launched");
	}

	@Override
	public String getLaunchedAction() {
		// TODO Auto-generated method stub
		return LoadBalance.class.getName();
	}


}
